import bus from "./bus";

interface ListenerFunction {
    (...args: any[]): void
}

interface EventBusListeners {
    [eventName: string]: ListenerFunction[]
}

export function useEventBus(): EventBus {
    const listeners: EventBusListeners = {};

    const $on = (eventName: string, listener: ListenerFunction): void => {
        if (!listeners[eventName]) {
            listeners[eventName] = [];
        }
        listeners[eventName].push(listener);
    };

    const $emit = (eventName: string, ...args: any[]): void => {
        const eventListeners = listeners[eventName];
        if (eventListeners) {
            eventListeners.forEach((listener) => {
                listener(...args);
            });
        }
    };
    //模糊匹配eventName,如果匹配上就发送
    const $emitVague= (eventName: string, ...args: any[]): void => {
        Object.keys(listeners).forEach(testEventName => {
            // console.log(`Event Name: ${eventName}`);
            if(testEventName.indexOf(eventName) > -1) {
                const eventListeners = listeners[testEventName];
                if (eventListeners) {
                    eventListeners.forEach((listener) => {
                        listener(...args);
                    });
                }
            }
        });
    };
    const $off = (eventName: string, listener?: ListenerFunction): void => {
        const eventListeners = listeners[eventName];
        if (eventListeners) {
            if (listener) {
                listeners[eventName] = eventListeners.filter((l) => l !== listener);
            } else {
                delete listeners[eventName];
            }
        }
    };
    const $exist = (eventName: string): boolean => {
        if (listeners[eventName] ){
            return true;
        }else{
            return false;

        }
    };
    return {
        $on,
        $emit,
        $off,
        $exist,
        $emitVague
    };
}

// EventBus 类型定义
export type EventBus = ReturnType<typeof useEventBus>;
const eventBus = useEventBus();
export default eventBus
